#!/home/cs1010/anaconda3/envs/mqtt_admin/bin/python

import time
import ssl
import paho.mqtt.client as mqtt
import configparser
import sys
import json

# 读取配置文件
def read_config(config_file):
    config = configparser.ConfigParser()
    config.read(config_file)
    mqtt_config = config['MQTT']
    mqtt_broker = mqtt_config.get('broker')
    mqtt_port = int(mqtt_config.get('port'))
    username = mqtt_config.get('username')
    password = mqtt_config.get('password')
    return mqtt_broker, mqtt_port, username, password

# 模拟设备 ID，实际使用时可替换为真实设备 ID
device_id = "device_12345"

# 配置文件路径
config_file = 'device_config.ini'
mqtt_broker, mqtt_port, username, password = read_config(config_file)

# 创建 MQTT 客户端实例
client = mqtt.Client(client_id=device_id)

# 连接成功回调函数
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
        # 订阅设备专属的激活话题
        activation_topic = f"device/{device_id}/activation"
        client.subscribe(activation_topic)
        # 发送设备 ID 到注册话题
        client.publish("device/register", device_id)
        print(f"Sent device ID {device_id} to server.")
    else:
        print(f"Failed to connect, return code {rc}")

# 接收到消息回调函数
def on_message(client, userdata, msg):
    if msg.topic.startswith(f"device/{device_id}/activation"):
        try:
            # 解码接收到的消息
            activation_code = msg.payload.decode()
            # 解析 JSON 数据
            activation_data = json.loads(activation_code)
            print(f"Received activation code: {activation_data}")
            # 提取具体信息
            rdevice_id = activation_data.get("device_id")
            app_id = activation_data.get("app_id")
            room_id = activation_data.get("room_id")
            uid = activation_data.get("uid")
            token = activation_data.get("token")
            print(f"rdevice_id: {rdevice_id}, App ID: {app_id}, Room ID: {room_id}, UID: {uid}, Token: {token}")
        except json.JSONDecodeError:
            print("Failed to decode JSON data from the received message.")
        # 停止循环
        client.loop_stop()
        # 断开连接
        client.disconnect()

# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message

# 设置 TLS/SSL 配置
client.tls_set(cert_reqs=ssl.CERT_NONE)
client.tls_insecure_set(True)

# 设置用户名和密码
client.username_pw_set(username, password)

# 连接到 MQTT 服务器
try:
    client.connect(mqtt_broker, mqtt_port)
    # 启动循环处理网络流量
    client.loop_start()
    while True:
        time.sleep(1)
except Exception as e:
    print(f"Connection error: {e}")
finally:
    # 停止循环
    client.loop_stop()
    # 断开连接
    client.disconnect()
    